<template>
  <u-form>
    <u-icon name="arrow-up" size="28" :color="flagColor"></u-icon>
    <u-form-item label="料架" prop="rackCode">
      <u-input v-model="form.rackCode" placeholder="请扫描料架" :readonly="initFlag"/>
    </u-form-item>
    <u-form-item label="条码" prop="qrCode">
      <u-input v-model="form.qrCode" placeholder="请扫描物料条码" :readonly="initFlag"/>
    </u-form-item>
    <u-divider text="分割线" :dot="true"></u-divider>
    <u-form-item  prop="setting">
      <u-row>
        <u-col >尾料<u-switch   v-model="form.isTailings"></u-switch></u-col>
        <u-col >不回传<u-switch  v-model="form.text7"></u-switch></u-col>
      </u-row>
    </u-form-item>
    <u-form-item label="物料" prop="materielCD">
      <u-input v-model="form.data.materielCD" placeholder="请输入物料编码" :readonly="initFlag"/>
    </u-form-item>
    <u-form-item label="数量" prop="materielQTY">
      <u-input v-model="form.data.materielQTY" placeholder="请输入数量" :readonly="initFlag"/>
    </u-form-item>
    <u-form-item label="供应" prop="brand">
      <u-input v-model="form.data.brand" placeholder="请输入供应商" :readonly="initFlag"/>
    </u-form-item>
    <u-form-item label="订单" prop="ordernumber">
      <u-input v-model="form.data.ordernumber" placeholder="请输入采购订单号" :readonly="initFlag"/>
    </u-form-item>
    <u-divider text="分割线" :dot="true"></u-divider>
    <view class="fixed-bottom">
      <u-row>
        <u-col span="6"><u-button @click="addStockTask">上架</u-button></u-col>
        <u-col span="6"><u-button @click="cancelStockTask">取消上架</u-button></u-col>
      </u-row>
    </view>
  </u-form>
</template>
<script>
import UForm from "../../../../uview-ui/components/u-form/u-form.vue";
import UFormItem from "../../../../uview-ui/components/u-form-item/u-form-item.vue";
import UDivider from "../../../../uview-ui/components/u-divider/u-divider.vue";
import UIcon from "../../../../uview-ui/components/u-icon/u-icon.vue";
import URow from "../../../../uview-ui/components/u-row/u-row.vue";
import UCol from "../../../../uview-ui/components/u-col/u-col.vue";
import USwitch from "../../../../uview-ui/components/u-switch/u-switch.vue";
import UButton from "../../../../uview-ui/components/u-button/u-button.vue";
import {addTask, analysisQRCode, cancelTask, existTask} from "@/api/work/rack/rackUtil";

export default {
  name: 'index',
  components: {UButton, USwitch, UCol, URow, UIcon, UDivider, UFormItem, UForm},
  data () {
    return {
      initFlag: false,
      form: {
        qrCode: null,
        rackCode: null,
        isTailings: false,
        text7: false,
        data: {
          materielCD: null,
          materielQTY: null,
          brand: null,
          ordernumber: null,
        }
      },
      flagColor: 'green',
      rackRegex:  /^L(0[1-9]|1[0-6])[AB]$/,
      qrCodeRegex: /(.{0,25}#){8}(all|ALL)/,
    }
  },
  onLoad(){
    try {
      this.initScan();
      this.initFlag = true;
    } catch (e) {
      this.$modal.showToast('该类型设备暂不支持红外扫码', e)
    }
  },
  beforeDestroy() {
    if (this.initFlag) {
      let globalEvent = uni.requireNativePlugin('globalEvent');
      globalEvent.removeEventListener('iDataBarcodeEvent', this.handlePdaScan);
    }
  },
  methods: {
    initScan() {
      let barcodeModel = uni.requireNativePlugin("iData-BarcodePlugin-BarcodeModule")
      barcodeModel.initScan((ret) => {
        if (ret.code === 'success') {
          console.log("初始化成功");
        }
      });
      barcodeModel.setOutputMode(4,(ret) => {
        if (ret.code === 'success') {
          console.log("模式设置成功");
        }
      });
      let globalEvent = uni.requireNativePlugin('globalEvent');
      let that = this;
      this.handlePdaScan = function(res) {
        that.checkSearchKey(res.barcode);
      }
      globalEvent.addEventListener('iDataBarcodeEvent', this.handlePdaScan);
    },
    checkSearchKey(qrCode) {
      if (this.flagColor !== 'green') {
        uni.showToast({icon: 'none', title: '存在任务，请取消'})
        return;
      }
      if (this.rackRegex.test(qrCode)) {
        this.form.rackCode = qrCode;
        return;
      }
      this.form.qrCode = qrCode;
      if (this.qrCodeRegex.test(qrCode)) {
        analysisQRCode(qrCode).then(res => {
          if (res.status === '0') {
            this.form.data = res.data;
            this.addStockTask();
          } else {
            this.$modal.msgError(res.error);
          }
        });
        return;
      }
      uni.showToast({icon: 'none', title: "数据不符合格式：" + qrCode})
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    },
    async checkTask(rackCode, invCode) {
      let forFlag = true;
      let index = 0;

      while (forFlag) {
        const res = await existTask(rackCode, invCode);
        if (res.data !== true) {
          this.$modal.msgSuccess('任务消失');
          forFlag = false;
          this.flagColor = 'green';
          this.resetFormData();
        }
        // 实现暂停1秒
        await this.sleep(1000);
        // 每次循环后增加index并判断是否需要停止循环
        if (index++ > 60) {
          forFlag = false;
          this.flagColor = 'green';
        }
      }
    },
    existTask(rackCode, invCode) {
      // 模拟异步请求
      return new Promise((resolve) => {
        // 这里应该有调用实际API的逻辑
        existTask(rackCode, invCode).then(() => {
          resolve({res: /* 根据实际情况 */ false});
        });
      });
    },
    addStockTask() {
      if (!this.form.rackCode) {
        uni.showToast({icon: 'none', title: '料架不能为空'})
        return;
      }
      if (!this.form.data.materielCD) {
        uni.showToast({icon: 'none', title: '物料编码不能为空'})
        return;
      }
      if (!this.form.data.materielQTY) {
        uni.showToast({icon: 'none', title: '物料数量不能为空'})
        return;
      }
      this.form.data.text7 = this.form.text7? '1':'0';
      this.form.data.isTailings = this.form.isTailings?'1':'0';
      addTask(this.form).then(res => {
        if (res.status === '0') {
          this.$modal.msgSuccess( "开始上架");
          this.flagColor = 'red';
          // 遍历任务是否存在
          let rackCode = this.form.rackCode;
          let invCode = this.form.data.materielCD;
          this.checkTask(rackCode, invCode);
        } else {
          uni.showToast({icon: 'none', title: res.error})
        }
      });
    },
    cancelStockTask() {
      if (!this.form.rackCode) {
        uni.showToast({icon: 'none', title: '料架不能为空'})
      }
      cancelTask(this.form.rackCode).then(() => {
        this.$modal.msgSuccess( "取消成功");
        this.flagColor = 'green';
        this.resetFormData();
      });
    },
    resetFormData() {
      this.form.data = {
        materielCD: null,
        materielQTY: null,
        brand: null,
        ordernumber: null,
      };
    }
  }
}
</script>
<style>
.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  /* 可能需要设置一些内边距或外边距以保持良好的视觉效果 */
  padding: 10px;
  text-align: center;
  background-color: #fff; /* 背景色与页面背景色相同或透明，视设计而定 */
  z-index: 999; /* 确保按钮在最上层 */
}
</style>
